import React, { Component } from 'react'
import './index.scss'
import * as racketActions from '../../actions/racket' 
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
class Racket extends Component {
    constructor (props) {
        super(props)
        this.state = {
            racketImg: require('../../assets/imgs/racket.png'),
            x: 500,
            width: 120,
            height: 16
        }
    }
    // shouldComponentUpdate (nextProps) {
        // const half = this.state.width / 2
        // if (nextProps.mousePosition <= half || nextProps.mousePosition >= nextProps.wrapWidth - half) {
        //     return false
        // }
        // return true
    // }
    componentDidMount() {
        this.bindEvent()
    }   
    bindEvent () {
        // const { wrapWidth } = this.props
        // console.log(wrapWidth)
        const { width } = this.state
        const gameContainer = document.getElementById('game-container')
        // 问题:事件冒泡 解决：地图置底
        gameContainer.addEventListener('mousemove',(e) => {
            // e.stopPropagation()
            // 问题：setState异步 鼠标先移动 板后移动 判断不准
            // const { x } = this.state
            if (e.offsetX <=  width / 2 || e.offsetX >= this.props.wrapWidth - width / 2) return
            // 异步 
            this.setState({
                x: e.offsetX
            })
            this.props.racketActions.moveRacket(e.offsetX)
        })
    }
        render() {
        const { racketImg, width, height, x } = this.state
        return (
            <div className="racket-box" style={{
                width,
                height,
                left: x - width / 2
                // top: this.props.wrapHeight - 18
            }}>
                    <img src={racketImg} alt="" />
            </div>
        )
    }
}

const mapAction = (dispatch) => {
    return {
        racketActions: bindActionCreators(racketActions, dispatch)
    }
    
}

export default connect(null,mapAction)(Racket)
